from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from ..models  import Users
# 密码加密 | 密码解密
from django.contrib.auth.hashers import make_password, check_password
from django.core.urlresolvers import reverse

from . IndexViews import uploads
import os
from django.db.models import Q
from django.contrib.auth.decorators import permission_required


@permission_required('myadmin.insert_users',raise_exception = True)
# 用户添加 显示添加页面
def user_add(request):
    return render(request,'admin/users/add.html')

@permission_required('myadmin.insert_users',raise_exception = True)
# 会员添加
def user_insert(request):
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    # 密码加密
    data['password'] = make_password(data['password'], None, 'pbkdf2_sha256') 
    # 图片名字创建
    myfile = request.FILES.get('pic',None)
    if myfile:
        data['pic'] = uploads(myfile)
    else:
        data['pic'] = "/static/pics/"+"user.jpg"

    Users.objects.create(**data)

    return HttpResponse('<script>location.href="'+reverse('myadmin_user_index')+'"</script>')

@permission_required('myadmin.show_users',raise_exception = True)
# 显示所有会员
# 功能:1.显示所有会员 
#           按照要求每页显示 n 个会员
#      2.接受页面传入信息 请求 types(当前页面数) keywords(搜索类别) biao(搜索条件)   
def user_index(request):

    # 获取数据库所有数据
    users = Users.objects.all()

    # 搜索模块
    # 接受参数 types(搜索类别) keywords(搜索条件)
    types   = request.GET.get('types',None)
    keywords = request.GET.get('keywords',None) 
    # 判断是否有搜索条件
    if types:
        if types == 'all':
            users = users.filter(Q(username__contains=keywords)|Q(age__contains=keywords)|Q(phone__contains=keywords)|Q(email__contains=keywords))            
        elif types == 'username':
            users = users.filter(username__contains=keywords)
        elif types == 'age':
            users = users.filter(age__contains=keywords)
        elif types == 'phone':
            users = users.filter(phone__contains=keywords)
        elif types == 'email':
            users = users.filter(email__contains=keywords)


    # 数据分页 模块 
    from django.core.paginator import Paginator
    # 实例化分页对象,参数1,数据列表  参数2 每页显示的条数
    p = Paginator(users, 10)
    # 获取当前的页码数
    page = request.GET.get('biao',1)
    page = int(page)
    # 获取当前页的数据
    userlist = p.page(page)
    # 获取所有的页码列表
    pages = p.page_range

    # 将分好的数据装入 字典 返回给页面
    info = {'data':userlist}
    return render(request,'admin/users/index.html',info)
    
@permission_required('myadmin.del_users',raise_exception = True)
# 删除会员
def user_deluser(request):
    import os
    uid = request.GET.get('uid')
    n = Users.objects.get(id=uid).pic

    if n == "/static/pics/user.jpg":
        pass
    else:
        os.remove("."+n)

    Users.objects.get(id=uid).delete()
    return HttpResponse('<script>location.href="'+reverse('myadmin_user_index')+'"</script>')

@permission_required('myadmin.edit_users',raise_exception = True)
# 修改会员信息
def user_setuser(request):
    uid = request.GET.get('uid')
    us = Users.objects.get(id=uid)
    data = {'info':us}
    return render(request,'admin/users/set.html',data)

@permission_required('myadmin.edit_users',raise_exception = True)
# 更新会员信息
def user_uodate(request):
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')
    uid = data['id']

    # 获取页面传过来的头像信息
    myfile = request.FILES.get('pic',None)   
    # 获取图片名字
    tuname = str(myfile).split(' ')[0]
    # 获取要修改的id
    ku = Users.objects.get(id=uid)
    # 数据库表中 图片的名字
    n = ku.pic
    ku_name = ku.pic
    # 如果没改图片 tuname = None
    if myfile == None:
        # 如果没改图片 不做任何操作
        pass
    else:
        if n == '/static/pics/user.jpg':
            pass
        else:
            # 否则   删除文件中的图片
            os.remove("./"+n) 
        # 把新图片 编辑放入数据库
        # 图片名字创建
        myfile = request.FILES.get('pic',None)
        from . IndexViews import uploads
        ku.pic = uploads(myfile)
        
    ku.username = data['username']
    ku.phone = data['phone']
    ku.email = data['email']
    ku.sex = data['sex']
    ku.age = data['age']
    ku.save()

    return HttpResponse('<script>location.href="'+reverse('myadmin_user_index')+'"</script>')



